/*
 * portscan.c
 * Copyright (c) 2010 Peter Polacik <polacik.p@gmail.com>
 *
 * This file is part of AIC Library
 *
 * Licensed under MIT License, see LICENSE for more information.
 */

#include <libaic.h>
#include <port.h>

int *scan(char *addr ,int port_min, int port_max, unsigned int type)
{
	int i, rval;
	int ret[port_max - port_min];
	memset(&ret, 0, sizeof(ret));
	for (i = port_min; i <= port_max; i++) {
		rval = doscan(addr, type, i);
		if (rval == -2)
			ret[i-port_min] = ERR_SCAN_TYPE;
		else if (rval != -1) ret[i-port_min] = 1;
	}
	return ret;
}

int doscan(char *addr, int type, int port)
{
	switch (type) {
		case 0 : return scan_con(addr, port);
			break;
		default : return -2;
	}
	return -2;
}

int scan_con(char *addr, int port)
{
	int sock, rval;
	struct hostent *hostaddr;
	struct sockaddr_in servaddr;
	sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (sock == -1) {
		return errno;
	}
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	hostaddr = gethostbyname(addr);
	memcpy(&servaddr.sin_addr, hostaddr->h_addr, hostaddr->h_length);
	rval = connect(sock, (struct sockaddr *) &servaddr, sizeof(servaddr));
	close(sock);
	return rval;
}
